package com.lej.core.widget.customview

import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
import com.lej.core.R


/**依据高度设定宽度尺寸*/
class RatioImageView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : AppCompatImageView(context, attrs, defStyleAttr) {
    private var scale = 0f

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        if (scale != 0f) {
            val wms = MeasureSpec.makeMeasureSpec(
                (MeasureSpec.getSize(heightMeasureSpec) * scale).toInt(),
                MeasureSpec.EXACTLY
            )
            super.onMeasure(wms, heightMeasureSpec)
            return
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    }

    init {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.RatioImageView)
        scale = typedArray.getFloat(R.styleable.RatioImageView_scale, scale)
        typedArray.recycle()
    }

    fun setScale(scale: Float) {
        this.scale = scale
    }
}